package com.shop.resource.service.impl;

import com.shop.resource.service.IEmailService;
import com.shop.resource.util.emiltool.EmailConfig;
import com.teemor.common.bean.model.EmailModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 *
 * @author zhoulk
 * @date: 2019年05月08日  17:19
 */
@Service
public class EmailService implements IEmailService {

    private static final Logger LOGGER = LoggerFactory.getLogger(EmailService.class);

    @Autowired
    Configuration configuration; //freeMarker configuration
    @Autowired
    private EmailConfig emailConfig;
    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void sendEmail(EmailModel emailModel) {
        Map<String, Object> map = new HashMap<>();

        map.put("time", new Date(emailModel.getTimestamp()));
        map.put("message", emailModel.getMsg());
        map.put("toUserName", StringUtils.isNotBlank(emailModel.getUserName())? emailModel.getUserName() : emailModel.getAddress());
        sendHtmlMail(emailModel.getAddress(), emailModel.getTitle(), map, "model.ftl");
    }

    private void sendHtmlMail(String to, String subject, Map<String, Object> map, String model) {
        MimeMessage message = mailSender.createMimeMessage();
        Template t; // freeMarker template
        try {
            t = configuration.getTemplate(model);
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(t, map);
            setInfoByHelper(to, subject, content, message);
            mailSender.send(message);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    private void setInfoByHelper(String to, String subject, String content, MimeMessage message)
            throws MessagingException {
        //true表示需要创建一个multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(emailConfig.getEmailFrom());
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
    }
}
